import axios from 'axios';
import config from '../config';
import { ElMessage } from 'element-plus';

import router from './../router'
import storage from './storage'

const TOKEN_INVALID = 'Token认证失败,请重新登录';
const NETWORK_ERROR = '网络异常请请稍候重试';
// 创建axios实例对象，添加全局配置
const service = axios.create({
  baseURL: config.baseApi,
  timeout: 60000,
  // headers:{'x-Custom-Header':'foobar'}
});
// 请求拦截
service.interceptors.request.use((req) => {
  
  
  const headers = req.headers;
  if (!headers.Authorization) headers.Authorization = 'Bear Jack';
  return req;
});
// 响应拦截
service.interceptors.response.use((res) => {


  if(res.data.hasOwnProperty("code")){

    const { code, data, msg } = res.data;
    if (code == 200) {
      return data;
    }
    
    else if (code == 50001) {
      ElMessage.error(TOKEN_INVALID);
      setTimerout(() => {
        router.push('/login');
      }, 1500);
      return Promise.reject(TOKEN_INVALID);
    }
    else {
      ElMessage.error(msg || NETWORK_ERROR);
      return Promise.reject(msg || NETWORK_ERROR);
    }
  }else // 检查HTTP状态码
  if (res.status === 200) {
    return res.data;
  } else if (res.status === 50001) {
    ElMessage.error(TOKEN_INVALID);
    setTimeout(() => {
      router.push('/login');
    }, 1500);
    return Promise.reject(TOKEN_INVALID);
  } else {
    ElMessage.error(NETWORK_ERROR);
    return Promise.reject(NETWORK_ERROR);
  }


  
});

 
 



function request(options) {
  options.method = options.method || 'get'
  if (options.method.toLowerCase() === 'get') {
      options.params = options.data;
  }
  let isMock = config.mock;
  if (typeof options.mock != 'undefined') {
      isMock = options.mock;
  }
  if (config.env === 'prod') {
      service.defaults.baseURL = config.baseApi
  } else {
      service.defaults.baseURL = isMock ? config.mockApi : config.baseApi
  }

  return service(options)
}


['get', 'post', 'put', 'delete', 'patch'].forEach((item) => {
  request[item] = (url, data, options) => {
      return request({
          url,
          data,
          method: item,
          ...options
      })
  }
})
export default request;